$(function () {
//声明变量
    //表格
    var pro_datagrid =$("#pro_datagrid");
    var member_datagrid =$("#member_datagrid");
    var onAccountTable =$("#onAccountTable");
    //弹出框
    var memberList_dialog =$("#memberList_dialog");
    var member_dialog =$("#member_dialog");
    //表单
    var dictionary_form = $("#dictionary_form");

    //公共变量商铺name
    var shopName;
    //清空输入的方法
    function empty(){

        $.each($("#bill_table tr"),function (index, tr) {
            $(tr).find("[tag='salePrice']").val('');
            $(tr).find("[tag='number']").val('');
            $(tr).find("[name='name']").val('');
            $(tr).find("[name='amount']").val('');
            $(tr).find("[tag='pid']").val('');
            if (index > 1) {
                $(tr).remove();
            }
        });
    }
    //改变总价显示的方法
    function changetotal(){
        var total = 0;
            $.each($("#bill_table tr"),function (index, tr) {
                total+=(parseFloat($(tr).find("[name='amount']").val())?parseFloat($(tr).find("[name='amount']").val()):0);
            });
           $("#totalAmount_span").html(total);
    }
    //===========商品明细绑定事件=============
    $("#add").click(function () {
        var num =$(this).closest("tr").find("#num").val();
        var salePrice =$(this).closest("tr").find("#salePrice").val();
        $(this).closest("tr").find("#num").val(num*1+1);
        $(this).closest("tr").find("#amount").val((num*1+1)*salePrice);
        changetotal();
    });

    $("#del").click(function () {
        var num =$(this).closest("tr").find("#num").val();
        var salePrice =$(this).closest("tr").find("#salePrice").val();
        $(this).closest("tr").find("#num").val(num*1-1);
        $(this).closest("tr").find("#amount").val((num*1-1)*salePrice);
        changetotal()
        if($("#bill_table tr").size()!= 2 && num <= 0){
            $(this).closest("tr").remove();
        }
    });
    function change() {
        var num =$(this).closest("tr").find("#num").val();
        var salePrice =$(this).closest("tr").find("#salePrice").val();
    }


    //===================================右侧面板:选项卡========================================
    //===================================右侧面板:商品列表========================================

    pro_datagrid.datagrid({
        url:'/product/query.do',
        fit:true,
        fitColumns:true,
        pagination:true,
        rownumber:true,
        singleSelect:true,
        columns:[[
            {field:'id',checkbox:true},
            {field:'name',title:'商品姓名',width:80},
            {field:'sn',title:'商品编码',width:80},
            {field:'costPrice',title:'商品进价',width:80},
            {field:'salePrice',title:'销售单价',width:80},
            {field:'classify',title:'一级类别',width:80,formatter:function (value,row,index) {
                    //当前对象是否存在
                    return value? value.classname:'';
                }},
            {field:'shop',title:'所属店铺',width:80,formatter:function (value,row,index) {
                    return value? value.name:'';
                }}
        ]],
        onClickRow:function (index,row) {
            //获取所有的tr
            var trs = $("#bill_table tr");
            var index = 0;
            var start = 0;
            //获取购物明细中所有id数组
            var ids = $.map(trs,function (ele) {
                start = start+1;
                if($(ele).find("[name='id']").val() == row.id){
                    index = start;
                }
                return $(ele).find("[name='id']").val();
            });
            var hasid = false;
            $.map(ids,function (ele) {
                if(ele == row.id){
                    hasid = true;
                }
            });
            //根绝点击id,查询是否有重复的行在表单内
            if(hasid){
                //明细中有重复,改为增加商品数量
                var numinput = $(trs[index - 1]).find("input[name='num']");
                numinput.val(numinput.val()*1 +1);//数量甲乙
                $.each($("#bill_table tr"),function (index,ele) {
                    if ($(ele).find("#bill_id").val() == row.id) {
                        var num =$(ele).find("#num").val();
                        var salePrice =$(ele).find("#salePrice").val();
                        $(ele).find("#amount").val(num*salePrice);
                    }
                });

            }else{
                //如果第一行有值,则克隆一个新行
                if ($(trs[1]).find("[name='id']").val()){
                    var newtr = $(trs[1]).clone(true);
                    newtr.find("input").val('');
                    newtr.find("#add").val('增');
                    newtr.find("#del").val('减');
                    newtr.appendTo("#bill_table");
                }
                $("#bill_table tr:last-child").find("#bill_id").val(row.id);
                $("#bill_table tr:last-child").find("#salePrice").val(row.salePrice);
                $("#bill_table tr:last-child").find("#name").val(row.name);
                $("#bill_table tr:last-child").find("#num").val(1);
                var num =$("#bill_table tr:last-child").find("#num").val();
                var salePrice =$("#bill_table tr:last-child").find("#salePrice").val();
                $("#bill_table tr:last-child").find("#amount").val(num*salePrice);
            }
            changetotal();
        }
    });
    //===================================右侧面板:会员列表========================================
    member_datagrid.datagrid({
        url:'/member/selectAllByShopName.do',
        fit:true,
        fitColumns:true,
        pagination:true,
        rownumber:true,
        singleSelect:true,
        columns:[[
            {field:'id',checkbox:true},
            {field:'cardNumber',title:'会员卡号',width:80},
            {field:'name',title:'会员名称',width:80},
            {field:'tel',title:'电话',width:80},
            {field:'balance',title:'余额',width:80},
            {field:'address',title:'地址',width:80},
            {field:'points',title:'积分',width:80}
        ]],
        onClickRow:function (index,row){
            //获取选中行的数据,赋值给会员信息
            $("#memberMsg_div :input[name='cardNumber']").val(row.cardNumber);
            $("#memberMsg_div :input[name='name']").val(row.name);
            $("#memberMsg_div :input[name='balance']").val(row.balance);

            //点击后关闭弹窗
            memberList_dialog.dialog('close');
        }
    });

    //=================================取单-->挂单表格========================================
    onAccountTable.datagrid({
        url:'/cashier/listAll.do',
        fit:true,
        fitColumns:true,
        pagination:true,
        singleSelect:true,
        columns:[[
            {field:'id',checkbox:true},
            {field:'vdate',title:'挂单日期',width:80},
            {field:'member',title:'会员卡号',width:80,formatter:function (value,row,index) {
                    //当前对象是否存在
                    return value? value.cardNumber:'';
                }},
            {field:'member',title:'会员名称',width:80,formatter:function (value,row,index) {
                    //当前对象是否存在
                    return value? value.name:'';
                }},
            {field:'shop_name',title:'商店名称',width:80},
            {field:'saleman',title:'挂单人',width:80,formatter:function (value,row,index) {
                    //当前对象是否存在
                    return value? value.realname:'';
                }}
        ]],
        onClickRow:function (index,row){
            //获取选中行的数据,赋值给会员信息
            $("#memberMsg_div :input[name='cardNumber']").val(row.member.cardNumber);
            $("#memberMsg_div :input[name='name']").val(row.member.name);
            $("#memberMsg_div :input[name='balance']").val(row.member.balance);
            $("#shopInfo").combobox('setValue',row.shop_name);
            var trs = $("#bill_table tr");
            //数据
            $.each(row.items,function (i,n) {
                //如果第一行有值,则克隆一个新行
                if ($(trs[1]).find("[name='id']").val()){
                    var newtr = $(trs[1]).clone(true);
                    newtr.find("input").val('');
                    newtr.find("#add").val('增');
                    newtr.find("#del").val('减');
                    newtr.appendTo("#bill_table");
                }
                $("#bill_table tr:last-child").find("#billitem_id").val(row.id);
                $("#bill_table tr:last-child").find("#bill_id").val(n.product.id);
                $("#bill_table tr:last-child").find("#salePrice").val(n.salePrice);
                $("#bill_table tr:last-child").find("#name").val(n.product.name);
                $("#bill_table tr:last-child").find("#num").val(n.number);
                var num = n.number;
                var salePrice = n.salePrice;
                $("#bill_table tr:last-child").find("#amount").val(num*salePrice);
            });
            changetotal();
            //点击后关闭弹窗
            member_dialog.dialog('close');
        }
    });
   //=======================================挂单================================================
    var methodObj = {
        stay:function(){ //挂单
            //获取一行数据
            var row = $("#bill_table tr:last-child").find("#num").val();
            //判断是否有选择选择数据
            if (!(row > 0)) {
                //没有选择数据提示用户
                $.messager.alert("温馨提示", "至少选择一件商品", "warning");
                return;//终止操作
            }
            //弹出确认框
            $.messager.confirm('确认', '您确认想要挂单吗？', function (r) {
                if (r) {
                    $("#cardNumber").val($("#memberInfo").val());
                    $("#shopName").val($("#shopInfo").val());
                    $.each($("#bill_table tr"),function (index, tr) {
                        $(tr).find("[tag='salePrice']").prop("name","items["+(index-1)+"].salePrice");
                        $(tr).find("[tag='number']").prop("name","items["+(index-1)+"].number");
                        $(tr).find("[tag='pid']").prop("name","items["+(index-1)+"].product.id");
                    });
                    //给后台发送后台
                    $('#bill_form').form('submit', {
                        url:"/cashier/onAccount.do",
                        success: function(data){
                            data=$.parseJSON(data);
                            if (data.success) {
                                $.messager.alert('温馨提示', '操作成功', 'info', function () {
                                    //加载刷新到当前界面
                                    empty();
                                })
                            } else {
                                $.messager.alert("温馨提示", data.msg, "error");
                            }
                        }

                    });
                }
            })
        },
        getpay:function (){
            //取单
            member_datagrid.datagrid('reload');
            member_dialog.dialog('open');
        },
        pay:function (){

            //提交表单
            //获取店铺值
            shopName = $("#memberMsg_div :input[name='shopName']").val();
            console.log(shopName);
            if (shopName == null || shopName == '') {
                //没有选择数据提示用户
                $.messager.alert("温馨提示", "请选择店铺", "warning");
                return;//终止操作
            }
            var row = $("#bill_table tr:last-child").find("#num").val();
            //判断是否有选择选择数据
            if (!(row > 0)) {
                //没有选择数据提示用户
                $.messager.alert("温馨提示", "至少选择一件商品", "warning");
                return;//终止操作
            }
            //============================更改付款的参数形式=================================
            //支付,获取传递后台的数据给表单
            $("#cardNumber").val($("#memberInfo").val());
            $("#shopName").val($("#shopInfo").val());
            $.each($("#bill_table tr"),function (index, tr) {
                $(tr).find("[tag='salePrice']").prop("name","items["+(index-1)+"].salePrice");
                $(tr).find("[tag='number']").prop("name","items["+(index-1)+"].number");
                $(tr).find("[tag='pid']").prop("name","items["+(index-1)+"].product.id");
            });
            //给后台发送后台
            $.messager.confirm('确认', '您确认想要付款吗？', function (r){
                if (r) {
                    $('#bill_form').form('submit', {
                        url:"/cashier/payAccount.do",
                        success: function(data){
                            data=$.parseJSON(data);
                            if (data.success) {
                                $.messager.alert('温馨提示', '操作成功', 'info', function () {
                                    //加载刷新到当前界面
                                    $(this).closest("iframe").prop('src',"/cashier/view.do");
                                    member_datagrid.datagrid('reload');
                                    empty();
                                })
                            } else {
                                $.messager.alert("温馨提示", data.msg, "error");
                            }
                        }

                    });
                }
            });

        },
        memberMsg:function () {
            //获取店铺值
            shopName = $("#memberMsg_div :input[name='shopName']").val();
            console.log(shopName);
            if (shopName == null || shopName == '') {
                //没有选择数据提示用户
                $.messager.alert("温馨提示", "请选择店铺", "warning");
                return;//终止操作
            }

            member_datagrid.datagrid('reload',{
                shopName: shopName
            });
            memberList_dialog.dialog('open');
        },
        cancel: function (){
            //关闭弹出框:
            dictionary_dialog.dialog('close');
        }
    };
    //统一绑定事件:
    $("a[data-cmd]").click(function () {
        var methodname = $(this).data("cmd");
        //动态获取调用方法名字,调用方法;
        methodObj[methodname]();
    });

    //======================================会员相关===============================================
    //会员,挂单弹出框
        member_dialog.dialog({
        width:700,
        height:500,
            close:true
    });
    //会员列表弹出框
    memberList_dialog.dialog({
        width:700,
        height:500,
        close:true
    });
    //=============================================================================================


});


